package com.um.springboot.starter.utils;

/**
 *
 * @author 邓南辉
 * 日期 2021/4/10
 * 版权所有 广州优匠科技有限公司
 */
public class NameUtils {

    /**
     * 根据骆驼命名规则的属性名转为下划线的表列名，如：userName => user_name
     * @param propertyName
     * @return
     */
    public static String getColumnName(String propertyName) {
        if (null == propertyName) {
            return "";
        }

        StringBuilder sbl = new StringBuilder(propertyName);
        sbl.setCharAt(0, Character.toLowerCase(sbl.charAt(0)));
        propertyName = sbl.toString();

        char[] chars = propertyName.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (char c : chars) {
            if (c >= 'A' && c <= 'Z') {
                sb.append("_").append(String.valueOf(c).toLowerCase());
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 根据数据库列表转为骆驼命名规则的属性名
     * @param fieldName
     * @return
     */
    public static String getPropertyName(String fieldName) {
        if (null == fieldName) {
            return "";
        }
        fieldName = fieldName.toLowerCase();
        char[] chars = fieldName.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '_') {
                int j = i + 1;
                if (j < chars.length) {
                    sb.append(String.valueOf(chars[j]).toUpperCase());
                    i++;
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
